package com.hzmall.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import sun.rmi.runtime.Log;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CookieUtil {
    private static String COOKIE_NAME="user_login_cookie";
    private static String COOKIE_DOMAIN="ccdemo.s1.natapp.cc";

    //用于登录成功后写入浏览器Cookie信息
    public static void setCookie(HttpServletResponse response, String token){
        Cookie cookie = new Cookie(COOKIE_NAME,token);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        cookie.setDomain(COOKIE_DOMAIN);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    //用于权限验证时，从浏览器读取Cookie信息
    public static String readCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), COOKIE_NAME)) {
                    log.info("读取Cookie成功,Value={}",cookie.getValue());
                    return cookie.getValue(); //token
                }
            }
        }
        return null;
    }

    //从浏览器中移除Cookie信息
    public static void deleteCookie(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies){
                if (StringUtils.equals(cookie.getName(),COOKIE_NAME)){
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    cookie.setDomain(COOKIE_DOMAIN);
                    response.addCookie(cookie);
                    return;
                }
            }
        }
    }
}
